package com.zbkj.crmeb.store.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.store.dao.ActivityProductDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.ActivityProductEnrollRequest;
import com.zbkj.crmeb.store.request.ActivityProductSearchRequest;
import com.zbkj.crmeb.store.response.ActivityVerifyResponse;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityProductServiceImpl extends ServiceImpl<ActivityProductDao, ProductEnroll> implements ActivityProductService {
    @Resource
    private ActivityProductDao activityProductDao;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private UserService userService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private ActivityManageService activityManageService;

    /**
     * 审核分页查询
     *
     * @param @param request pageParamRequest
     * @return PageInfo<ActivityVerifyResponse>
     * @Description:
     * @author duyb
     * @Date: 2022-11-10
     */
    @Override
    public PageInfo<ActivityVerifyResponse> verifyPageEntity(ActivityProductSearchRequest request, PageParamRequest pageParamRequest) {

        List<ProductEnroll> productEnrollList = this.list(Wrappers.<ProductEnroll>lambdaQuery()
                .eq(ProductEnroll::getStatus, 1)
                .orderByDesc(ProductEnroll::getId));
        if (CollectionUtils.isEmpty(productEnrollList)) {
            return CommonPage.copyPageInfo(PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit()), new ArrayList<>());
        }
        List<Integer> userIdList = productEnrollList.stream().map(ProductEnroll::getEnrollUserId).distinct().collect(Collectors.toList());
        List<SystemAdmin> adminList = systemAdminService.list(Wrappers.<SystemAdmin>lambdaQuery()
                .in(SystemAdmin::getId, userIdList)
        );
        List<String> merIdList = adminList.stream().map(SystemAdmin::getMerId).distinct().collect(Collectors.toList());
        List<Integer> merIds = new ArrayList<>();
        for (String s : merIdList) {
            List<Integer> list = JSONArray.parseArray(s, Integer.class);
                merIds.add(list.get(0));
        }
        List<ChannelMerchant> merList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                .in(CollectionUtils.isNotEmpty(merIds), ChannelMerchant::getId, merIds)
        );

        Map<Integer, String> map = new HashMap<>();
        // 获取店铺名称(已去重)
        for (SystemAdmin admin : adminList) {
            for (ChannelMerchant merchant : merList) {
                if (Objects.equals(JSONArray.parseArray(admin.getMerId(), Integer.class).get(0), merchant.getId())) {
                    map.put(admin.getId(), merchant.getChannelName());
                }
            }
        }
        // 获取商品相关信息
        List<Integer> productIdList = productEnrollList.stream().map(ProductEnroll::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .in(StoreProduct::getId, productIdList)
        );
        //匹配商品图片
        productConvertUtil.convertProductImage(productList);
        Map<Integer, StoreProduct> productMap = new HashMap<>();
        for (StoreProduct product : productList) {
            productMap.put(product.getId(), product);
        }

        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIdList)
        );
        Map<Integer, List<StoreProductAttrValueResponse>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValueResponse> list = new ArrayList<StoreProductAttrValueResponse>();
                    StoreProductAttrValueResponse response = new StoreProductAttrValueResponse();
                    BeanUtils.copyProperties(s, response);
                    list.add(response);
                    return list;
                },
                (List<StoreProductAttrValueResponse> value1, List<StoreProductAttrValueResponse> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        //获取价格区间
        Map<Integer, Map<String, Object>> attrMap = new HashMap<>();
        for (Integer key : attrValueMap.keySet()) {
            Map<String, Object> priceMap = new HashMap<>();
            List<StoreProductAttrValueResponse> storeProductAttrValueResponses = attrValueMap.get(key);
            Integer stock = 0;
            for (int i = 0; i < storeProductAttrValueResponses.size(); i++) {
                StoreProductAttrValueResponse attr = storeProductAttrValueResponses.get(i);
                stock += attr.getStock();
                if (i == 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                    priceMap.put("minPrice", attr.getPrice());
                    continue;
                }
                //下一个sku的价格比最低价小
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("minPrice")) < 0) {
                    priceMap.put("minPrice", attr.getPrice());
                }
                //下一个sku价格比最高价大
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("maxPrice")) > 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                }
            }
            priceMap.put("stock", stock);
            attrMap.put(key, priceMap);
        }


        List<ActivityVerifyResponse> activityVerifyResponseList = new ArrayList<>();
        for (ProductEnroll productEnroll : productEnrollList) {
            ActivityVerifyResponse activityVerifyResponse = new ActivityVerifyResponse();
            BeanUtils.copyProperties(productEnroll, activityVerifyResponse);
            activityVerifyResponse.setStoreName(map.get(productEnroll.getEnrollUserId()));
            activityVerifyResponse.setProductName(productMap.get(productEnroll.getProductId()).getStoreName());
            activityVerifyResponse.setImage(productMap.get(productEnroll.getProductId()).getImage());
            activityVerifyResponse.setMaxPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("maxPrice"));
            activityVerifyResponse.setMinPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("minPrice"));
            activityVerifyResponse.setStock((Integer) attrMap.get(productEnroll.getProductId()).get("stock"));
            activityVerifyResponseList.add(activityVerifyResponse);
        }

        if (StringUtils.isNotBlank(request.getStoreName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getStoreName().contains(request.getStoreName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getProductName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getProductName().contains(request.getProductName())).collect(Collectors.toList());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (!Objects.isNull(request.getEnrollTime())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> Objects.equals(format.format(o.getEnrollTime()), request.getEnrollTime())).collect(Collectors.toList());
        }


        //分页处理
        int pageNum = pageParamRequest.getPage();
        int limit = pageParamRequest.getLimit();
        int start = (pageNum - 1) * limit;
        int end = pageNum * limit;
        if (end>activityVerifyResponseList.size()){
            end=activityVerifyResponseList.size();
        }
        Page<Object> page = PageHelper.startPage(pageNum, limit);
        page.setTotal(activityVerifyResponseList.size());
        activityVerifyResponseList = activityVerifyResponseList.subList(start,end);
        return CommonPage.copyPageInfo(page, activityVerifyResponseList);
    }


    /**
     * 报名分页查询
     *
     * @param @param request pageParamRequest
     * @return PageInfo<ActivityVerifyResponse>
     * @Description:
     * @author duyb
     * @Date: 2022-11-10
     */
    @Override
    public PageInfo<ActivityVerifyResponse> enrollPageEntity(ActivityProductSearchRequest request, PageParamRequest pageParamRequest) {
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<ProductEnroll> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!Objects.isNull(request.getStatus())) {
            lambdaQueryWrapper.like(ProductEnroll::getStatus, request.getStatus());
        }
        lambdaQueryWrapper.eq(ProductEnroll::getEnrollUserId,systemAdminService.getAdminId());
        lambdaQueryWrapper.orderByDesc(ProductEnroll::getId);
        List<ProductEnroll> productEnrollList = this.list(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(productEnrollList)) {
            return CommonPage.copyPageInfo(page, new ArrayList<>());
        }
        // 获取商品相关信息
        List<Integer> productIdList = productEnrollList.stream().map(ProductEnroll::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .in(StoreProduct::getId, productIdList)
        );
        //匹配商品图片
        productConvertUtil.convertProductImage(productList);
        Map<Integer, StoreProduct> productMap = new HashMap<>();
        for (StoreProduct product : productList) {
            productMap.put(product.getId(), product);
        }

        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIdList)
        );
        Map<Integer, List<StoreProductAttrValueResponse>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValueResponse> list = new ArrayList<StoreProductAttrValueResponse>();
                    StoreProductAttrValueResponse response = new StoreProductAttrValueResponse();
                    BeanUtils.copyProperties(s, response);
                    list.add(response);
                    return list;
                },
                (List<StoreProductAttrValueResponse> value1, List<StoreProductAttrValueResponse> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        //获取价格区间
        Map<Integer, Map<String, Object>> attrMap = new HashMap<>();
        for (Integer key : attrValueMap.keySet()) {
            Map<String, Object> priceMap = new HashMap<>();
            List<StoreProductAttrValueResponse> storeProductAttrValueResponses = attrValueMap.get(key);
            Integer stock = 0;
            for (int i = 0; i < storeProductAttrValueResponses.size(); i++) {
                StoreProductAttrValueResponse attr = storeProductAttrValueResponses.get(i);
                stock += attr.getStock();
                if (i == 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                    priceMap.put("minPrice", attr.getPrice());
                    continue;
                }
                //下一个sku的价格比最低价小
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("minPrice")) < 0) {
                    priceMap.put("minPrice", attr.getPrice());
                }
                //下一个sku价格比最高价大
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("maxPrice")) > 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                }
            }
            priceMap.put("stock", stock);
            attrMap.put(key, priceMap);
        }


        List<ActivityVerifyResponse> activityVerifyResponseList = new ArrayList<>();
        for (ProductEnroll productEnroll : productEnrollList) {
            ActivityVerifyResponse activityVerifyResponse = new ActivityVerifyResponse();
            BeanUtils.copyProperties(productEnroll, activityVerifyResponse);
            activityVerifyResponse.setProductName(productMap.get(productEnroll.getProductId()).getStoreName());
            activityVerifyResponse.setImage(productMap.get(productEnroll.getProductId()).getImage());
            activityVerifyResponse.setMaxPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("maxPrice"));
            activityVerifyResponse.setMinPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("minPrice"));
            activityVerifyResponse.setStock((Integer) attrMap.get(productEnroll.getProductId()).get("stock"));
            activityVerifyResponseList.add(activityVerifyResponse);
        }

        if (StringUtils.isNotBlank(request.getStoreName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getStoreName().contains(request.getStoreName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getProductName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getProductName().contains(request.getProductName())).collect(Collectors.toList());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (!Objects.isNull(request.getEnrollTime())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> Objects.equals(format.format(o.getEnrollTime()), request.getEnrollTime())).collect(Collectors.toList());
        }

        return CommonPage.copyPageInfo(page, activityVerifyResponseList);
    }


    /**
     * 活动商品分页查询
     *
     * @param @param request pageParamRequest
     * @return PageInfo<ActivityManageResponse>
     * @Description:
     * @author duyb
     * @Date: 2022-11-10
     */
    @Override
    public PageInfo<ActivityVerifyResponse> pageEntity(ActivityProductSearchRequest request, PageParamRequest pageParamRequest) {

        List<ProductEnroll> productEnrollList = this.list(Wrappers.<ProductEnroll>lambdaQuery()
                .eq(ProductEnroll::getStatus, 2)
                .orderByDesc(ProductEnroll::getId));
        if (CollectionUtils.isEmpty(productEnrollList)) {
            return CommonPage.copyPageInfo(PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit()), new ArrayList<>());
        }
        //获取报名用户
        List<Integer> userIdList = productEnrollList.stream().map(ProductEnroll::getEnrollUserId).distinct().collect(Collectors.toList());
        List<SystemAdmin> adminList = systemAdminService.list(Wrappers.<SystemAdmin>lambdaQuery()
                .in(SystemAdmin::getId, userIdList)
        );
        List<String> merIdList = adminList.stream().map(SystemAdmin::getMerId).distinct().collect(Collectors.toList());
        List<Integer> merIds=new ArrayList<>();
        for (String s : merIdList) {
            List<Integer> list = JSONArray.parseArray(s, Integer.class);
            merIds.add(list.get(0));
        }
        List<ChannelMerchant> merList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                .in(ChannelMerchant::getId, merIds)
        );

        Map<Integer, String> map = new HashMap<>();
        // 获取店铺名称(已去重)
        for (SystemAdmin admin : adminList) {
            for (ChannelMerchant merchant : merList) {
                if (Objects.equals(JSONArray.parseArray(admin.getMerId(), Integer.class).get(0), merchant.getId())) {
                    map.put(admin.getId(), merchant.getChannelName());
                }
            }
        }

        //获取活动状态
        List<Integer> activityIdList = productEnrollList.stream().map(ProductEnroll::getActivityId).distinct().collect(Collectors.toList());
        List<ActivityManage> activityManageList = activityManageService.list(Wrappers.<ActivityManage>lambdaQuery()
                .in(ActivityManage::getId, activityIdList)
        );
        HashMap<Integer, Integer> statusMap = new HashMap<>();
        for (ActivityManage activityManage : activityManageList) {
            if (activityManage.getActivityType()){
                statusMap.put(activityManage.getId(),2);
            }else if (DateUtil.isEffectiveDate(new Date(),activityManage.getActivityStartTime(),activityManage.getActivityEndTime())){
                statusMap.put(activityManage.getId(),2);
            }else if (DateUtil.compareDate(activityManage.getActivityStartTime(),new Date())){
                statusMap.put(activityManage.getId(),1);
            }else {
                statusMap.put(activityManage.getId(),3);
            }
        }


        // 获取商品相关信息
        List<Integer> productIdList = productEnrollList.stream().map(ProductEnroll::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .in(StoreProduct::getId, productIdList)
        );
        //匹配商品图片
        productConvertUtil.convertProductImage(productList);
        Map<Integer, StoreProduct> productMap = new HashMap<>();
        for (StoreProduct product : productList) {
            productMap.put(product.getId(), product);
        }

        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIdList)
        );
        Map<Integer, List<StoreProductAttrValueResponse>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValueResponse> list = new ArrayList<StoreProductAttrValueResponse>();
                    StoreProductAttrValueResponse response = new StoreProductAttrValueResponse();
                    BeanUtils.copyProperties(s, response);
                    list.add(response);
                    return list;
                },
                (List<StoreProductAttrValueResponse> value1, List<StoreProductAttrValueResponse> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        //获取价格区间
        Map<Integer, Map<String, Object>> attrMap = new HashMap<>();
        for (Integer key : attrValueMap.keySet()) {
            Map<String, Object> priceMap = new HashMap<>();
            List<StoreProductAttrValueResponse> storeProductAttrValueResponses = attrValueMap.get(key);
            Integer stock = 0;
            for (int i = 0; i < storeProductAttrValueResponses.size(); i++) {
                StoreProductAttrValueResponse attr = storeProductAttrValueResponses.get(i);
                stock += attr.getStock();
                if (i == 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                    priceMap.put("minPrice", attr.getPrice());
                    continue;
                }
                //下一个sku的价格比最低价小
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("minPrice")) < 0) {
                    priceMap.put("minPrice", attr.getPrice());
                }
                //下一个sku价格比最高价大
                if (attr.getPrice().compareTo((BigDecimal) priceMap.get("maxPrice")) > 0) {
                    priceMap.put("maxPrice", attr.getPrice());
                }
            }
            priceMap.put("stock", stock);
            attrMap.put(key, priceMap);
        }


        List<ActivityVerifyResponse> activityVerifyResponseList = new ArrayList<>();
        for (ProductEnroll productEnroll : productEnrollList) {
            ActivityVerifyResponse activityVerifyResponse = new ActivityVerifyResponse();
            BeanUtils.copyProperties(productEnroll, activityVerifyResponse);
            activityVerifyResponse.setStoreName(map.get(productEnroll.getEnrollUserId()));
            activityVerifyResponse.setProductName(productMap.get(productEnroll.getProductId()).getStoreName());
            activityVerifyResponse.setImage(productMap.get(productEnroll.getProductId()).getImage());
            activityVerifyResponse.setMaxPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("maxPrice"));
            activityVerifyResponse.setMinPrice((BigDecimal) attrMap.get(productEnroll.getProductId()).get("minPrice"));
            activityVerifyResponse.setStock((Integer) attrMap.get(productEnroll.getProductId()).get("stock"));
            activityVerifyResponse.setActivityStatus(statusMap.get(productEnroll.getActivityId())==null?4:statusMap.get(productEnroll.getActivityId()));

            activityVerifyResponseList.add(activityVerifyResponse);
        }

        if (StringUtils.isNotBlank(request.getActivityName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getActivityName().contains(request.getActivityName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getStoreName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getStoreName().contains(request.getStoreName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getProductName())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> o.getProductName().contains(request.getProductName())).collect(Collectors.toList());
        }
        if (!Objects.isNull(request.getActivityStatus())) {
            activityVerifyResponseList = activityVerifyResponseList.stream().filter(o -> Objects.equals(o.getActivityStatus(), request.getActivityStatus())).collect(Collectors.toList());
        }


        //分页处理
        int pageNum = pageParamRequest.getPage();
        int limit = pageParamRequest.getLimit();
        int start = (pageNum - 1) * limit;
        int end = pageNum * limit;
        if (end>activityVerifyResponseList.size()){
            end=activityVerifyResponseList.size();
        }
        Page<Object> page = PageHelper.startPage(pageNum, limit);
        page.setTotal(activityVerifyResponseList.size());
        activityVerifyResponseList = activityVerifyResponseList.subList(start,end);
        return CommonPage.copyPageInfo(page, activityVerifyResponseList);
    }


    /**
     * 报名
     * @Description:
     * @author duyb
     * @param @param activityProductEnrollRequest
     * @return Boolean
     * @Date: 2022-11-10
     */
    @Override
    public Boolean saveEntity(ActivityProductEnrollRequest activityProductEnrollRequest) {
        if (CollectionUtils.isEmpty(activityProductEnrollRequest.getProductIds())) {
            throw new CrmebException("请选择商品!");
        }

        //商品不能重复报名
        List<ProductEnroll> productEnrollList = this.list(Wrappers.<ProductEnroll>lambdaQuery()
                .eq(ProductEnroll::getActivityId, activityProductEnrollRequest.getActivityId())
                .eq(ProductEnroll::getEnrollUserId, systemAdminService.getAdminId())
        );
        List<Integer> productIdList = productEnrollList.stream().map(ProductEnroll::getProductId).collect(Collectors.toList());
        List<ProductEnroll> productEnrolls = new ArrayList<>();
        for (Integer productId : activityProductEnrollRequest.getProductIds()) {
            out:
            if (productIdList.contains(productId)) {
                ProductEnroll one = this.getOne(Wrappers.<ProductEnroll>lambdaQuery()
                        .eq(ProductEnroll::getProductId, productId)
                        .eq(ProductEnroll::getActivityId, activityProductEnrollRequest.getActivityId())
                        .orderByDesc(ProductEnroll::getCreateTime)
                        .last("limit 1")
                );
                if (Objects.equals(one.getStatus(), 0)) {
                    break out;
                }
                continue;
            }

            ProductEnroll productEnroll = new ProductEnroll();
            BeanUtils.copyProperties(activityProductEnrollRequest, productEnroll);

            productEnroll.setProductId(productId);
            productEnroll.setStatus(1);
            productEnroll.setEnrollTime(new Date());
            productEnroll.setCreateTime(new Date());
            productEnroll.setUpdateTime(new Date());
            productEnroll.setEnrollUserId(systemAdminService.getAdminId());
            productEnrolls.add(productEnroll);
        }

        return this.saveBatch(productEnrolls);
    }


    /**
     * 批量审核
     * @Description:
     * @author duyb
     * @param @param productEnrollList
     * @return Boolean
     * @Date: 2022-11-11
     */
    @Override
    public Boolean batchVerify(List<Integer> productEnrollIdList) {
        if (CollectionUtils.isEmpty(productEnrollIdList)) {
            throw new CrmebException("请选择商品!");
        }

        //验证活动是否存在
        List<ProductEnroll> productEnrollList = this.list(Wrappers.<ProductEnroll>lambdaQuery()
                .in(ProductEnroll::getId, productEnrollIdList)
        );

        List<Integer> activityIdList = productEnrollList.stream().map(ProductEnroll::getActivityId).distinct().collect(Collectors.toList());
        int count = activityManageService.count(Wrappers.<ActivityManage>lambdaQuery()
                .in(ActivityManage::getId, activityIdList)
        );
        if (!Objects.equals(count, activityIdList.size())) {
            throw new CrmebException("活动不存在，无法通过!");
        }
        List<ActivityManage> activityManageList = activityManageService.list(Wrappers.<ActivityManage>lambdaQuery()
                .in(ActivityManage::getId, activityIdList)
        );
        ArrayList<Integer> verifyMap = new ArrayList<>();
        for (ActivityManage activityManage : activityManageList) {
            if (activityManage.getActivityType() || (DateUtil.isEffectiveDate(new Date(),activityManage.getActivityStartTime(),activityManage.getActivityEndTime()))){
                List<ProductEnroll> enrollList = this.list(Wrappers.<ProductEnroll>lambdaQuery()
                        .eq(ProductEnroll::getActivityId, activityManage.getId())
                        .in(ProductEnroll::getId, productEnrollIdList)
                );
                List<Integer> ids = enrollList.stream().map(ProductEnroll::getId).distinct().collect(Collectors.toList());
                verifyMap.addAll(ids);
            }
        }
        if (CollectionUtils.isEmpty(verifyMap)){
            return false;
        }

        return this.update(new UpdateWrapper<ProductEnroll>().lambda()
                .in(ProductEnroll::getId, verifyMap)
                .set(ProductEnroll::getStatus, 2)
                .set(ProductEnroll::getVerifyTime, new Date())
                .set(ProductEnroll::getVerifyUserId, systemAdminService.getAdminId())
        );
    }

    /**
     * 审核
     * @Description:
     * @author duyb
     * @param @param ActivityProductEnrollRequest
     * @return Boolean
     * @Date: 2022-11-11
     */
    @Override
    public Boolean verify(ActivityProductEnrollRequest request) {
        if (Objects.equals(request.getStatus(), 0) && StringUtils.isBlank(request.getRemark())) {
            throw new CrmebException("请填写驳回理由!");
        }

        ProductEnroll productEnroll = this.getById(request.getId());
        //验证活动是否存在
        ActivityManage activityManage = activityManageService.getById(productEnroll.getActivityId());
        if (Objects.isNull(activityManage)) {
            throw new CrmebException("活动不存在，无法通过!");
        }
        if (Objects.equals(request.getStatus(), 2) && !activityManage.getActivityType() && DateUtil.compareDate(new Date(),activityManage.getActivityEndTime())){
            throw new CrmebException("活动已结束，无法通过!");
        }
        return this.update(new UpdateWrapper<ProductEnroll>().lambda()
                .eq(ProductEnroll::getId, request.getId())
                .set(ProductEnroll::getStatus, request.getStatus())
                .set(ProductEnroll::getRemark, request.getRemark())
                .set(ProductEnroll::getVerifyTime, new Date())
                .set(ProductEnroll::getVerifyUserId, systemAdminService.getAdminId())
        );
    }


}
